<?php

declare(strict_types=1);

namespace App\Exception\Handler;

use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\ResponseInterface;
use Hyperf\HttpMessage\Exception\HttpException;
use Hyperf\Server\Exception\ServerException;
use Hyperf\HttpMessage\Exception\NotFoundHttpException;
use App\Exception\BusinessException;
use Throwable;

class HttpExceptionHandler extends ExceptionHandler
{
    public function handle(Throwable $throwable, ResponseInterface $response):ResponseInterface
    {
        //捕获服务器异常
        if ($throwable instanceof ServerException) {
            $data = json_encode([
                'code' => $throwable->getCode(),
                'message' => $throwable->getMessage(),
                'data' => []
            ],JSON_UNESCAPED_UNICODE);
            $this->stopPropagation();
            return $response->withStatus(200)->withBody(new SwooleStream($data));
        }
        if ($throwable instanceof NotFoundHttpException) {
            $data = json_encode([
                'code' => $throwable->getCode(),
                'message' => $throwable->getMessage(),
                'data' => null
            ],JSON_UNESCAPED_UNICODE);
            $this->stopPropagation();
            echo '这里异常了-0';
            return $response->withStatus(500)->withBody(new SwooleStream($data));
        }

        //捕获自定义异常
        if ($throwable instanceof BusinessException) {
            $data = json_encode([
                'code' => $throwable->getCode(),
                'message' => $throwable->getMessage(),
                'data' => null
            ],JSON_UNESCAPED_UNICODE);
            $this->stopPropagation();
            echo '这里异常了-1';
            return $response->withStatus(200)->withBody(new SwooleStream($data));
        } 

        //捕获HTTP异常
        if ($throwable instanceof HttpException) {
            $data = json_encode([
                'code' => $throwable->getCode(),
                'message' => "请求错误",
                'data' => null
            ],JSON_UNESCAPED_UNICODE);
            $this->stopPropagation();
            echo '这里异常了-2';
            return $response->withStatus(200)->withBody(new SwooleStream($data));
        }        

        // 交给下一个异常处理器
        return $response;
    }

    public function isValid(Throwable $throwable): bool
    {
        return true;
    }
}
